//
//  AppDelegate.m
//  A Learning Walk
//
//  Created by dllo on 16/6/13.
//  Copyright © 2016年 战斗民族. All rights reserved.
//

#import "AppDelegate.h"
#import "AllTabBarViewController.h"
#import "HRNavigationController.h"
#import "ZYPlayerViewController.h"
#import "UMSocial.h"
#import "Reachability.h"
#import "UMSocialWechatHandler.h"
//#import "UMSocialQQHandler.h"
//#import "UMSocialSinaSSOHandler.h"

#import <SMS_SDK/SMSSDK.h>

@interface AppDelegate ()<UITabBarControllerDelegate,EMChatManagerDelegate>// 环信签协议


{
   UIBackgroundTaskIdentifier _bgTaskId;
   Reachability *net;
}

@end

@implementation AppDelegate

-(void)dealloc{
    [_window release];
    [super dealloc];

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    /********************环信*************************/
    
    // 1.注册环信SDK
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"dlyutao#imyutao" apnsCertName:nil otherConfig:@{kSDKConfigEnableConsoleLogger:@(NO)}];
    // 让环信运行
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    // 2.监听自动登录的状态
    // 设置chatManager代理
    // 写个nil 默认代理会在主线程调用
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    // 3.如果登录过，直接来到主界面
    if ([[EaseMob sharedInstance].chatManager isAutoLoginEnabled]) {
        
    }

  
/********************友盟*************************/
    //设置友盟key
    [UMSocialData setAppKey:@"5764efa367e58e427800057f"];
    //打开调试
    [UMSocialData openLog:YES];
    
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:@"wx4e800b840d82e365" appSecret:@"3bee23c7e808035c5e63d416413d13f6" url:@"http://www.umeng.com/social"];
    
    
    
/************************友盟************************/

    NSString *appKey = @"1415878dd8fa6";
    NSString *appSecret = @"aad0a35d08ffc3e29a3cd0cbd652cb01";
    [SMSSDK registerApp:appKey withSecret:appSecret];
    
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    self.window.clipsToBounds = YES;
    
    [_window release];
    
    AllTabBarViewController *TabBarVC = [[AllTabBarViewController alloc] init];
    HRNavigationController *navi = [[HRNavigationController alloc] initWithRootViewController:TabBarVC];
    self.window.rootViewController = navi;
    TabBarVC.tabBar.dk_barTintColorPicker = DKColorPickerWithRGB(0xDCDCDC,0x696969);
    TabBarVC.delegate = self;
    [TabBarVC release];
    
    //音乐播放用
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     [defaults setObject:@"0" forKey:@"play"];
    // 判断登录状态
    [defaults setObject:@"0" forKey:@"isLogin"];
    
    //记录第一次进入工程
    [defaults setObject:@"YES" forKey:@"FirstTime"];
    [defaults setObject:@"NO" forKey:@"FirstPlay"];
     [defaults synchronize];
    //后台播放
    //开启后台处理多媒体事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    
    NSError* error = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    
    //这样做，可以在按home键进入后台后 ，播放一段时间，几分钟吧。但是不能持续播放网络歌曲，若需要持续播放网络歌曲，还需要申请后台任务id，具体做法是：
    _bgTaskId=[AppDelegate backgroundPlayerID:_bgTaskId];
    
    //拔出耳机停止播放
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];
  
    // ------开启网络状况监听
    [self startNetMonitor];
    
    return YES;
}

/**
 * 网络检测
 */
- (void)startNetMonitor {
    
    // ------开启网络状况监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange:) name:kReachabilityChangedNotification object:nil];
    net = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [net startNotifier];
    
}

- (void)networkStateChange:(NSNotification *)note
{
    Reachability *currReach = [note object];
    NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
    
    [self updateInterfaceWithReachability:currReach];
    
}
- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if (status == NotReachable) {
        
        // ------没有网络弹出提示框
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前网络不可用,请检查网络设置" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        
        [alertController addAction:cancelAction];
        
        [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
        
    }
}
//检测网络 -----------------------------------------------------------------

//拔下耳机就暂停
-(void)routeChange:(NSNotification *)notification{
    NSDictionary *dic=notification.userInfo;
    
    int changeReason= [dic[AVAudioSessionRouteChangeReasonKey] intValue];
    //等于AVAudioSessionRouteChangeReasonOldDeviceUnavailable表示旧输出不可用
    if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        AVAudioSessionRouteDescription *routeDescription=dic[AVAudioSessionRouteChangePreviousRouteKey];
        AVAudioSessionPortDescription *portDescription= [routeDescription.outputs firstObject];
        //原设备为耳机则暂停
        if ([portDescription.portType isEqualToString:@"Headphones"]) {
            //点击了暂停
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PlayChange" object:@"0"];
        }
    }
}

//实现一下backgroundPlayerID:这个方法:
+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
    //设置并激活音频会话类别
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    //允许应用程序接收远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    //设置后台任务ID
    UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
    newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
    }
    return newTaskId;
}

// 自动登陆的方法(环信)
-(void)didAutoLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error
{
    if (!error) {
        NSLog(@"自动登录成功 %@",loginInfo);
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:@"1" forKey:@"isLogin"];
    }else{
        NSLog(@"自动登录失败 %@",error);
    }
}

// 好友请求加你好友就会走的方法(环信)
- (void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message{
    // 打印请求加你好友的名字
    NSLog(@"%@",username);
    // 打印请求加你好友的信息
    NSLog(@"%@",message);
    // 将请求好友名字和请求好友信息加到字典中
    [self.buddy setObject:message forKey:username];
}
// 好友接收请求时的回调
- (void)didAcceptedByBuddy:(NSString *)username;
{
    NSLog(@"%@",username);
}
// 好友拒绝加你好友的回调
- (void)didRejectedByBuddy:(NSString *)username;
{
    NSLog(@"%@",username);
}


//友盟用回调方法
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}




- (void)applicationWillResignActive:(UIApplication *)application {
    
    //ZYPlayerViewController是我为播放器写的单例，这段就是当音乐还在播放状态的时候，给后台权限，不在播放状态的时候，收回后台权限
    //||[ZYPlayerViewController shareZYPlayerViewController].player.state == STKAudioPlayerStateBuffering||[ZYPlayerViewController shareZYPlayerViewController].player.state == STKAudioPlayerStatePaused ||[ZYPlayerViewController shareZYPlayerViewController].player.state == STKAudioPlayerStateStopped
    if ([ZYPlayerViewController shareZYPlayerViewController].player.state == STKAudioPlayerStatePlaying ) {
        //有音乐播放时，才给后台权限，不做流氓应用。
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [[UIApplication sharedApplication] ignoreSnapshotOnNextApplicationLaunch];
        [self becomeFirstResponder];
        [ZYPlayerViewController shareZYPlayerViewController].player.state = STKAudioPlayerStatePaused;

    }
    else
    {
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        [self resignFirstResponder];
        [ZYPlayerViewController shareZYPlayerViewController].player.state = STKAudioPlayerStateStopped;
    }
    
    
       
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}


/**
 *  响应远程音乐播放控制消息
 */
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {

    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlPause:
                //点击了暂停
                  [[NSNotificationCenter defaultCenter] postNotificationName:@"PlayChange" object:@"0"];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                //点击了下一首
              //  [self playNextMusic];
                 NSLog(@"1111");
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                //点击了上一首
             //`   [self playPreMusic];
                 NSLog(@"2222");
                break;
            case UIEventSubtypeRemoteControlPlay:
                //点击了播放
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PlayChange" object:@"1"];
              //  NSLog(@"2222");
                break;
            default:
                break;
        }
    
    
    }
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
